<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<div>
    <textarea style="width: 600px;height: 300px" id="message"></textarea>

    <P>消息是:</P>
    <div id="msg"></div>
</div>

<script>

const chancel =  "21435"
// 21435 模拟某个用户的ID , 当作一个频道
const source = new EventSource("/sse/event/" + chancel)

// 监听 流中的数据
source.onmessage = function(event){
    document.getElementById("msg").innerText += event.data ;
}

document.querySelector("#message").addEventListener("keydown", function(event){
    if (event.keyCode === 13) {

        const data = new URLSearchParams();
        data.append("message", this.value);
        data.append("channel", chancel);
        // 发送消息给 服务器
        fetch('/sse/message', {
            method: "POST",
            body: data,
        }).then(res => res.json())
            .then(ret => {
                this.value = "" ;
            })
    }
})

</script>
</body>
</html>